package com.zbkj.client.controller;

import com.zbkj.client.config.ClientTokenComponent;
import com.zbkj.client.service.*;
import com.zbkj.common.model.assets.Material;
import com.zbkj.common.model.assets.Knowledge;
import com.zbkj.common.model.assets.ClientProduct;
import com.zbkj.common.response.ClientLoginResponse;
import com.zbkj.common.response.client.AssetCountResponse;
import com.zbkj.common.result.CommonResult;
import com.zbkj.common.request.client.CreateFolderRequest;
import com.zbkj.common.vo.client.CreateFolderVo;
import com.zbkj.common.exception.CrmebException;
import com.zbkj.service.dao.client.CustomDigitalPersonDao;
import com.zbkj.service.service.CustomDigitalPersonService;
import com.zbkj.service.service.CustomVoiceService;
import com.zbkj.service.service.IntoPiecesService;
import com.zbkj.service.service.VideoTemplateFinalService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/client/assets")
@Api(tags = "资产管理")
public class AssetController {

    @Autowired
    private MaterialService materialService;

    @Autowired
    private ClientTokenComponent clientTokenComponent;

    @Autowired
    private KnowledgeService knowledgeService;

    @Autowired
    private ClientProductService clientProductService;

    @Autowired
    private VideoServiceCommon videoService;

    @Autowired
    private CustomDigitalPersonService customDigitalPersonService;

    @Autowired
    private CustomVoiceService customVoiceService;

    @Autowired
    private PieceService pieceService;

    @Autowired
    private IntoPiecesService intoPiecesService;

    @Autowired
    private VideoTemplateFinalService videoTemplateFinalService;


    @ApiOperation(value = "新建文件夹")
    @PostMapping("/createFolder")
    public CommonResult<Map<String, Object>> createFolder(@RequestBody CreateFolderRequest request, HttpServletRequest httpRequest) {
        Integer userId = clientTokenComponent.getLoginUser(httpRequest);
        if (userId == null) {
            return CommonResult.failed("用户未登录");
        }
        String type = request.getType();
        List<String> validTypes = new ArrayList<>();
        validTypes.add("knowledge");
        validTypes.add("product");
        validTypes.add("material");
        validTypes.add("template");
        validTypes.add("piece");

        if (!validTypes.contains(type.toLowerCase())) {
            return CommonResult.failed("参数错误");
        }
        String token = httpRequest.getHeader("token");
        ClientLoginResponse userInfo = clientTokenComponent.getUserInfo(userId, token);
        Integer merId = userInfo.getMerId();
        CreateFolderVo vo = new CreateFolderVo();
        vo.setUserId(userId);
        vo.setMerId(merId);
        vo.setParentId(request.getParentId());
        vo.setName(request.getName());

        boolean result;

        if ("knowledge".equalsIgnoreCase(type)) {
            result = knowledgeService.createFolder(vo);
        } else if ("product".equalsIgnoreCase(type)) {
            result = clientProductService.createFolder(vo);
        }else if ("template".equalsIgnoreCase(type)) {
            result = videoService.createFolder(vo);
        } else if ("piece".equalsIgnoreCase(type)) {
            result = pieceService.createFolder(vo);
        }else {
            result = materialService.createFolder(vo);
        }

        Map<String, Object> data = new HashMap<>();
        data.put("result", 1);

        return CommonResult.success(data);
    }

    @ApiOperation(value = "重命名文件")
    @PostMapping("/renameFile")
    public CommonResult<Map<String, Object>> renameFile(@RequestBody CreateFolderRequest request, HttpServletRequest httpRequest) {
        Integer userId = clientTokenComponent.getLoginUser(httpRequest);
        if (userId == null) {
            return CommonResult.failed("用户未登录");
        }
        String type = request.getType();
        List<String> validTypes = new ArrayList<>();
        validTypes.add("knowledge");
        validTypes.add("product");
        validTypes.add("material");
        validTypes.add("template");
        validTypes.add("piece");

        if (!validTypes.contains(type.toLowerCase())) {
            return CommonResult.failed("参数不存在");
        }
        String token = httpRequest.getHeader("token");
        ClientLoginResponse userInfo = clientTokenComponent.getUserInfo(userId, token);
        Integer merId = userInfo.getMerId();
        CreateFolderVo vo = new CreateFolderVo();
        vo.setUserId(userId);
        vo.setMerId(merId);
        vo.setParentId(request.getParentId());
        vo.setName(request.getName());
        vo.setId(request.getId());

        boolean result;

        if ("knowledge".equalsIgnoreCase(type)) {
            result = knowledgeService.renameFile(vo);
        } else if ("product".equalsIgnoreCase(type)) {
            result = clientProductService.renameFile(vo);
        } else if ("template".equalsIgnoreCase(type)) {
            result = videoService.renameFile(vo);
        } else if ("piece".equalsIgnoreCase(type)) {
            result = pieceService.renameFile(vo);
        }else {
            result = materialService.renameFile(vo);
        }

        Map<String, Object> data = new HashMap<>();
        data.put("result", 1);

        return CommonResult.success(data);
    }

    @ApiOperation(value = "批量移动文件夹")
    @PostMapping("/moveFolder")
    public CommonResult<Map<String, Object>> moveFolder(@RequestBody CreateFolderRequest request, HttpServletRequest httpRequest) {
        Integer userId = clientTokenComponent.getLoginUser(httpRequest);
        if (userId == null) {
            return CommonResult.failed("用户未登录");
        }

        String type = request.getType();
        List<String> validTypes = new ArrayList<>();
        validTypes.add("knowledge");
        validTypes.add("product");
        validTypes.add("material");
        validTypes.add("template");
        validTypes.add("piece");

        if (!validTypes.contains(type.toLowerCase())) {
            return CommonResult.failed("参数不存在");
        }

        List<Integer> ids = request.getIds();
        if (ids == null || ids.isEmpty()) {
            return CommonResult.failed("请选择要移动的文件夹");
        }

        if (request.getParentId() == null) {
            return CommonResult.failed("目标文件夹ID不能为空");
        }

        String token = httpRequest.getHeader("token");
        ClientLoginResponse userInfo = clientTokenComponent.getUserInfo(userId, token);
        Integer merId = userInfo.getMerId();

        CreateFolderVo vo = new CreateFolderVo();
        vo.setUserId(userId);
        vo.setMerId(merId);
        vo.setParentId(request.getParentId());
        vo.setName(request.getName());
        vo.setIds(ids);

        boolean result;
        try {
            if ("knowledge".equalsIgnoreCase(type)) {
                result = knowledgeService.batchMoveFolder(vo);
            } else if ("product".equalsIgnoreCase(type)) {
                result = clientProductService.batchMoveFolder(vo);
            } else if ("template".equalsIgnoreCase(type)) {
                result = videoService.batchMoveFolder(vo);
            } else if ("piece".equalsIgnoreCase(type)) {
                result = pieceService.batchMoveFolder(vo);
            }else {
                result = materialService.batchMoveFolder(vo);
            }
        } catch (CrmebException e) {
            return CommonResult.failed(e.getMessage());
        } catch (Exception e) {
            return CommonResult.failed("批量移动文件夹失败");
        }

        Map<String, Object> data = new HashMap<>();
        data.put("result", result ? 1 : 0);
        return CommonResult.success(data);
    }

    @ApiOperation(value = "资产统计总数")
    @GetMapping("/assetCount")
    public CommonResult<AssetCountResponse> assetCount(HttpServletRequest request) {
        Integer userId = clientTokenComponent.getLoginUser(request);
        if (userId == null) {
            return CommonResult.failed("用户未登录");
        }

        AssetCountResponse response = new AssetCountResponse();

        // 统计产品总数
        Integer productCount = clientProductService.countProductByUserId(userId);
        response.setProductCount(productCount != null ? productCount : 0);

        // 统计知识总数
        Integer knowledgeCount = knowledgeService.countKnowledgeByUserId(userId);
        response.setKnowledgeCount(knowledgeCount != null ? knowledgeCount : 0);

        // 统计素材总数
        Integer materialCount = materialService.countMaterialByUserId(userId);
        response.setMaterialCount(materialCount != null ? materialCount : 0);

        //统计音色总数
        Integer voiceCount = customVoiceService.countCustomVoiceByUserId(userId);
        response.setVoiceCount(voiceCount != null ? voiceCount : 0);

        //统计数字人形象总数
        Integer dpVideoCount = customDigitalPersonService.countCustomDpVideoByUserId(userId);
        response.setDpVideoCount(dpVideoCount != null ? dpVideoCount : 0);

        //统计成片总数
        Integer templateVedioCount = videoTemplateFinalService.countVideoTemplateByUserId(userId);
        response.setTemplateVideoCount(templateVedioCount != null ? templateVedioCount : 0);

        //成片总数
        Integer pieceCount = intoPiecesService.countPieceByUserId(userId);
        response.setPieceCount(pieceCount != null ? pieceCount : 0);

        return CommonResult.success(response);
    }
} 